layui.use(['admin', 'form', 'laydate', 'xmSelect', 'upload'], function () {
    let $            = layui.$
        , admin      = layui.admin
        , setter     = layui.setter
        , form       = layui.form
        , controller = '/admin/routine.config'
        , laytpl     = layui.laytpl
        , laydate    = layui.laydate
        , xmSelect   = layui.xmSelect
        , upload     = layui.upload
        , element    = layui.element
        , colorpicker= layui.colorpicker
        , router     = layui.router()
        , slider     = layui.slider
        , varName    = {}; // 动态变量名对象(存储组件的对象，方便后续操作组件)

    let parentNode = $('#configView');

    /**
     * 查询配置分组
     */
    let field = {};
    admin.req({
        url: setter.request.domainName + controller + '/index'
        , data: field
        , type: 'get'
        , loading: true // 是否开启加载框
        , is_message: false
        , done: function (res) {
            let tabList = [], list = [], getTpl, html;
            if (res.data.configGroup) {
                tabList = res.data.configGroup;
            }
            if (res.data.list) {
                list = res.data.list;
            }
            getTpl = configTpl.innerHTML;
            html = laytpl(getTpl).render({
                tabList: tabList,
                list: list,
            });
            parentNode.html(html);
            initDate('times'); // 初始化日期
            form.render(null, 'configPage'); //重载表格
            initXmSelect('xm-select', list); // 初始化xmSelect下拉选择框
            initWangEditor("wangEditor"); // 初始化wangEditor富文本编辑器
            initCity("city", list); // 初始化城市下拉选择框
            initImgUpload("uploadFile"); // 初始化图片、文件上传
            initColorPicker("colorPicker"); // 初始化颜色选择器
            initSwitch("switch"); // 初始化开关
            initSliderRange("slider-range", list); // 初始化滑块
            let layId = router.hash.replace(/^#layid=/, '');
            layId && element.tabChange('configTabs', layId);
        }
    })

    /**
     * 数组删除事件
     */
    window.delArray = function (e) {
        $(e).parents(".array_node").remove();
    }
    /**
     * 数组添加事件
     */
    window.addArray = function (e) {
        let that = $(e), id, name, html, _node;
        id = that.attr("data-id");
        name = that.attr("data-name");
        html = parentNode.find(".array_template").html();
        _node = parentNode.find(".array_" + id);
        _node.append(html);
        _node.children().each(function (j) {
            let keyName = name + "[" + j + "]['key']";
            let valueName = name + "[" + j + "]['value']";
            $(this).find(".array_key").attr('name', keyName);
            $(this).find(".array_value").attr('name', valueName);
        });
        return false;
    };

    /**
     * 初始化日期组件
     * @param class_name
     * @returns {boolean}
     */
    window.initDate = function (class_name) {
        let _node = parentNode.find('.' + class_name);
        _node.each((index, el) => {
            let type = $(el).attr("data-type"), dateType = "date", dataFormat = "";
            if (type === 'datetime' || type === 'time' || type === 'year' || type === 'month') {
                dateType = type;
            } else if (type === 'hour') {
                dateType = 'time';
                dataFormat = "H";
            } else if (type === 'minute') {
                dateType = 'time';
                dataFormat = "HH:mm";
            }
            if (dataFormat && dateType) {
                // 日期
                laydate.render({
                    elem: el
                    , trigger: 'click'
                    , type: dateType
                    , format: dataFormat
                });
            } else {
                laydate.render({
                    elem: el
                    , trigger: 'click'
                    , type: dateType
                });
            }
        });
    };

    /**
     * 初始化xmSelect下拉选择框
     * @param class_name // class名称
     * @param list
     */
    window.initXmSelect = function (class_name, list) {
        let _node = parentNode.find('.' + class_name);
        if (_node.length <= 0) {
            return false;
        }
        _node.each((index, el) => {
            let type           = $(el).attr("data-type")
                , key          = $(el).attr("data-key")
                , id           = $(el).attr("data-id")
                , tip          = $(el).attr("data-tip")
                , flag         = $(el).attr("data-flag")
                , name         = "xmSelect" + id
                , initData     = []
                , checkValue   = []
                , isRadio      = true
                , isClickClose = true;
            try {
                initData = list[flag]['list'][key]['content'];
            } catch (e) {

            }
            try {
                checkValue = list[flag]['list'][key]['value'];
            } catch (e) {

            }
            if (type === 'xm-selects') {
                isRadio = false;
                isClickClose = false;
            }
            varName[name] = xmSelect.render({
                el,
                prop: {
                    name: 'name',
                    value: 'key',
                },
                language: 'zn',
                autoRow: true, // 自动换行
                filterable: true, // 开启搜索模式
                paging: true, // 开启分页
                pageSize: 50, // 每页显示条数
                initValue: checkValue, // 默认选中
                radio: isRadio, // 开启单选
                clickClose: isClickClose, // 单选完关闭下拉
                max: 0, // 多选上限
                tips: tip,
                empty: "暂无数据",
                toolbar: {
                    show: true, // 显示工具条
                    list: ['ALL', 'CLEAR', 'REVERSE'], // 全选、清空、反选
                },
                data: initData,
                on: function (data) {
                    // change, 此次选择变化的数据,数组
                    let arr = data.arr;
                    let isAdd = data.isAdd;
                    let ids = '';
                    if(isAdd && arr.length > 0){
                        $.each(arr, function (i, j) {
                            let key = j.key;
                            if(ids === ''){
                                ids = key;
                            }else{
                                ids +=  "," + key;
                            }
                        })
                    }

                    parentNode.find("#xmSelectTxt"+id).val(ids);
                }
            });
        })
    }

    /**
     * 初始化wangEditor富文本编辑器
     * @param class_name // class名称
     */
    window.initWangEditor = function (class_name) {
        const { createEditor, createToolbar } = window.wangEditor
        let _node = parentNode.find('.' + class_name);
        let token = layui.data(setter.tableName)[setter.request.tokenName];
        let tokenName = setter.request.tokenName;
        let field = {server: true};
        field[tokenName] = token;
        if (_node.length <= 0) {
            return false;
        }
        _node.each((index, el) => {
            let id = $(el).attr("data-id");
            let tip = $(el).attr("data-tip");
            let nodeStr = "#wangEditor_" + id;
            let _node = parentNode.find(nodeStr);
            let toolbarNodeStr = "#wangEditor_toolbar_" + id;
            let toolbarNode = parentNode.find(toolbarNodeStr);
            let _nodeLen = _node.length;
            let toolbarNodeLen = toolbarNode.length;
            if (_nodeLen <= 0 || _nodeLen > 1 || toolbarNodeLen <= 0 || toolbarNodeLen > 1) {
                return false;
            }
            const editorConfig = {
                placeholder: tip ? tip : '请输入内容',
                autoFocus: true,
                MENU_CONF: {
                    uploadImage: {
                        server: setter.request.domainName + '/admin/Ajax/editorUpload',
                        timeout: 60 * 1000, // 超时时间(毫秒)
                        fieldName: 'file',
                        meta: field,
                        metaWithUrl: true,
                        headers: { Accept: 'text/x-json' },
                        maxFileSize: setter.maxFileSize * 1024 * 1024, // 20M // 最大文件大小
                        base64LimitSize: 0, // 10kb 以下插入 base6
                        onBeforeUpload(file) {
                            console.log('file')
                            return file;
                        },
                        // 上传进度的回调函数
                        onProgress(progress) {
                            console.log('onProgress', progress)
                        },
                        onSuccess(file, res) {
                            console.log('onSuccess', file, res)
                        },
                        onFailed(file, res) {
                            alert(res.message)
                            console.log('onFailed', file, res)
                        },
                        onError(file, err, res) {
                            alert(err.message)
                            console.error('onError', file, err, res)
                        },
                    },
                    uploadVideo: {

                    }
                },
                onChange(editor) {
                    const html = editor.getHtml()
                    // 也可以同步到 <textarea>
                    parentNode.find("#wangEditor_txt_" + id).val(html);
                }
            }

            let content = parentNode.find("#wangEditor_txt_" + id).val();

            let editor = createEditor({
                selector: nodeStr,
                html: '<p><br></p>',
                config: editorConfig,
                mode: 'default', // or 'simple'
            })
            const toolbarConfig = {}
            const toolbar = createToolbar({
                editor,
                selector: toolbarNodeStr,
                config: toolbarConfig,
                mode: 'default', // or 'simple'
            })
            editor.setHtml(content);
        })
    }

    /**
     * 初始化城市下拉选择框
     * @param class_name // class名称
     * @param list
     */
    window.initCity = function (class_name, list) {
        let _node = parentNode.find('.' + class_name);
        if (_node.length <= 0) {
            return false;
        }
        admin.req({
            url: setter.request.domainName + '/admin/Ajax/area'
            , data: {}
            , type: 'post'
            , loading: true // 是否开启加载框
            , is_message: false
            , done: function (res) {
                _node.each((index, el) => {
                    let type = $(el).attr("data-type");
                    let key = $(el).attr("data-key");
                    let id = $(el).attr("data-id");
                    let tip = $(el).attr("data-tip");
                    let flag = $(el).attr("data-flag");
                    let name = "xmSelect" + id;
                    let initData;
                    let checkValue;
                    try {
                        initData = res.data;
                    } catch (e) {
                        initData = []
                    }
                    try {
                        checkValue = list[flag]['list'][key]['value'];
                    } catch (e) {
                        checkValue = []
                    }
                    let isRadio = true;
                    let isClickClose = true;
                    if (type === 'xm-selects') {
                        isRadio = false;
                        isClickClose = false;
                    }
                    varName[name] = xmSelect.render({
                        el,
                        prop: {
                            name: 'label',
                            value: 'value',
                        },
                        language: 'zn',
                        autoRow: true, // 自动换行
                        filterable: true, // 开启搜索模式
                        paging: true, // 开启分页
                        pageSize: 50, // 每页显示条数
                        initValue: checkValue, // 默认选中
                        radio: isRadio, // 开启单选
                        clickClose: isClickClose, // 单选完关闭下拉
                        max: 0, // 多选上限
                        tips: tip,
                        empty: "暂无数据",
                        toolbar: {
                            show: true, // 显示工具条
                            list: ['ALL', 'CLEAR', 'REVERSE'], // 全选、清空、反选
                        },
                        data: initData,
                        on: function (data) {
                            // change, 此次选择变化的数据,数组
                            let arr = data.arr;
                            let isAdd = data.isAdd;
                            let ids = '';
                            if(isAdd && arr.length > 0) {
                                $.each(arr, function (i, j) {
                                    let value = j.value;
                                    if (ids === '') {
                                        ids = value;
                                    } else {
                                        ids += "," + value;
                                    }
                                })
                            }
                            parentNode.find("#cityIdTxt"+id).val(ids);
                        }
                    });
                })
            }
        })
    }

    /**
     * 图片上传
     * @param class_name
     */
    window.initImgUpload = function (class_name = '') {
        let _node = parentNode.find('.' + class_name);
        let token = layui.data(setter.tableName)[setter.request.tokenName];
        let tokenName = setter.request.tokenName;
        if (_node.length <= 0) {
            return false;
        }
        _node.each((index, el) => {
            let id = $(el).attr("data-id");
            let type = $(el).attr("data-type");
            let acceptMime = "image/jpeg,image/png,image/jpg";
            let exts = "jpeg|jpg|png";
            let accept = "images";
            if(type === 'file' || type === 'files'){
                acceptMime = "";
                exts = "";
                accept = "file";
            }
            upload.render({
                elem: el
                ,url: setter.request.domainName + '/admin/Ajax/upload?server=true&' + tokenName + '=' + token
                ,accept: accept
                ,acceptMime: acceptMime
                ,exts: exts
                ,size: setter.maxFileSize * 1024
                ,before: function(obj){
                    // 预读本地文件示例，不支持ie8
                    // obj.preview(function(index, file, result){
                    //     $('#upload-normal-img').attr('src', result); //图片链接（base64）
                    // });
                }
                ,done: function(res){
                    //如果上传失败
                    if(res.code === 1){
                        let full_url = res.data.file.full_url;
                        let url = res.data.file.url;
                        let fileName = res.data.file.name;

                        let html = '';
                        html += '<div class="img-div">';
                        if(type === 'file' || type === 'files') {
                            html += '<img class="layui-upload-img" style="width: 100px" id="upload_file' + id + '" alt="' + fileName + '" src="../static/images/file.png">';
                        }else{
                            html += '<img class="layui-upload-img" id="upload_file' + id + '" alt="' + fileName + '" src="' + full_url + '">';
                        }
                        html += '   <a href="javascript:void(0)" class="layui-icon layui-icon-delete del_show" style="display: block"  data-id="'+ id +'" data-type="'+ type +'"></a>';
                        html += '   <div class="ellipsis">' + fileName + '</div>';
                        html += '   <input type="hidden" class="fileList'+ id +'" value="'+ url +'">';
                        html += '</div>';

                        if(type === 'image' || type === 'file'){
                            parentNode.find("#upload_file_more_list" + id).html(html);
                        }else if(type === 'images' || type === 'files'){
                            parentNode.find("#upload_file_more_list" + id).append(html);
                        }

                        let fileUrlStr = '';
                        $(el).parent().find(".img-div").children('.fileList'+ id).each(function () {
                            let url = $(this).val();
                            if(fileUrlStr === ''){
                                fileUrlStr = url;
                            }else{
                                fileUrlStr += "," + url;
                            }
                        })
                        parentNode.find("#fileUrl" + id).val(fileUrlStr);
                        return layer.msg('上传成功！');
                    }else{
                        return layer.msg('上传失败！');
                    }
                    //上传成功
                }
                ,error: function(){
                    //演示失败状态，并实现重传
                    // uploadInst.upload(); // 重新上传
                }
            });
        })
    }

    /**
     * 初始化颜色选择器
     * @param class_name
     */
    window.initColorPicker = function (class_name = '') {
        let _node = parentNode.find('.' + class_name);
        if (_node.length <= 0) {
            return false;
        }
        _node.each((index, el) => {
            let id = $(el).attr("data-id");
            let color = parentNode.find("#colorText" + id).val();
            colorpicker.render({
                elem: el,
                color: color,
                predefine: true,
                alpha: true,
                done: function(color){
                    // layer.msg('选择的值：'+ color); // 选择完毕的颜色值
                    parentNode.find("#colorText" + id).val(color);
                    // 清空或取消选择时也执行 change
                    color || this.change(color);
                },
                change: function(color){
                    // 给当前页面头部和左侧设置主题色
                },
                cancel: function(color){ // 取消颜色选择的回调 --- 2.8+
                    this.change(color);
                }
            });
        })
    }

    /**
     * 初始化开关
     * @param class_name
     */
    window.initSwitch = function (class_name = '') {
        let _node = parentNode.find('.' + class_name);
        if (_node.length <= 0) {
            return false;
        }
        _node.each((index, el) => {
            let filter = $(el).attr("lay-filter");
            let id = $(el).attr("data-id");
            form.on('switch('+ filter +')', function(data){
                let status = 2;
                if(this.checked){
                    status = 1;
                }
                parentNode.find("#switchConfig" + id).val(status);
            });
        })
    }

    /**
     * 初始化滑块范围
     * @param class_name
     * @param list
     */
    window.initSliderRange = function (class_name = '', list = []){
        let _node = parentNode.find('.' + class_name);
        if (_node.length <= 0) {
            return false;
        }
        _node.each((index, el) => {
            let key            = $(el).attr("data-key")
                , id           = $(el).attr("data-id")
                , flag         = $(el).attr("data-flag")
                , min          = 0
                , max          = 100
                , checkValue   = [];
            try {
                let initData = list[flag]['list'][key]['content'];
                min = parseInt(initData.min);
                max = parseInt(initData.max);
            } catch (e) {

            }
            let _rInode = $("#slider-range-input-" + id);
            try {
                let str = _rInode.val();
                let arr = [];
                if(str.length > 0){
                    arr = str.split(" - ");
                }
                if(arr.length > 0){
                    checkValue = arr;
                    _rInode.val(arr[0] + ' 至 ' + arr[1]);
                }
            } catch (e) {

            }
            slider.render({
                elem: el
                ,min: min
                ,max: max
                ,value: checkValue //初始值
                ,range: true //范围选择
                ,change: function(value){
                    let val = value[0] + ' 至 ' + value[1];
                    _rInode.val(val);
                    val = value[0] + ' - ' + value[1];
                    $("#slider-range-val" + id).val(val);
                }
            });
        })
    }

    parentNode.on("click", ".del_show", function (j) {
        let id = $(this).attr("data-id");
        let fileUrlStr = "";
        $(this).parent().children('.fileList'+ id).each(function () {
            let url = $(this).val();
            if(fileUrlStr === ''){
                fileUrlStr = url;
            }else{
                fileUrlStr += "," + url;
            }
        })
        parentNode.find("#fileUrl" + id).val(fileUrlStr);
        $(this).parent(".img-div").remove();
    })

    window.submitForm = function (flag) {
        // 编辑提交
        form.on('submit('+flag+'Submit)', function (data) {
            let field = data.field; //获取提交的字段
            console.log(field);
            // 提交 Ajax 成功后，关闭当前弹层并重载表格
            admin.req({
                url: setter.request.domainName + controller + '/submitData' //实际使用请改成服务端真实接口
                , data: field
                , type: 'POST'
                , loading: true // 是否开启加载框
                , done: function(res){
                    layui.table.reload(''); //重载表格
                    admin.message({
                        title: '提交成功'
                        ,offset: '15px'
                        ,icon: 1
                        ,time: 1500
                    })
                }
            })
        });
    }
    element.on('tab(configTabs)', function(elem){
        location.hash = '/'+ layui.router().path.join('/') + '#layid=' + $(this).attr('lay-id');
    });

})
